<script setup>
import { KeyOutlined, LogoutOutlined, ProfileOutlined, UserOutlined } from '@ant-design/icons-vue'
import { sm4 } from 'gm-crypt'
import { updatePwd } from '~@/api/system/index'

const message = useMessage()
const userStore = useUserStore()
const multiTabStore = useMultiTab()
const layoutMenuStore = useLayoutMenu()
const router = useRouter()
const { avatar, username, userId } = storeToRefs(userStore)
const passwordForm = ref()
const passwordOpen = ref(false)// 修改密码
const formState = reactive({
  userId,
  oldPwd: '',
  newPwd: '',
  confirmPass: '',
})
const Secret = new sm4({
  key: 'FA171555405706F7', // 这里这个key值要与后端的一致，后端解密是根据这个key
  mode: 'ecb', // 加密的方式有两种，ecb和cbc两种，也是看后端如何定义的
  cipherType: 'base64',
})
const rules = computed(() => {
  return {
    oldPwd: [
      { required: true, message: '请输入旧密码', trigger: 'change' },
    ],
    newPwd: [
      { required: true, message: '请输入新密码', trigger: 'change' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPass: [
      {
        required: true, // ✅ 用来显示 *，不单独触发校验
        message: '',
        trigger: 'change',
      },
      {
        validator: (rule, value) => {
          if (!value) {
            return Promise.reject('请确认密码')
          }
          if (value !== formState.newPwd) {
            return Promise.reject('两次输入的密码不一致')
          }
          return Promise.resolve()
        },
        trigger: ['blur', 'change'],
      },

    ],

  }
})
async function handleClick({ key }) {
  if (key === 'logout') {
    const hide = message.loading('退出登录...', 0)
    try {
      await userStore.logout()
    }
    finally {
      hide()
      // message.success('退出登录成功', 3)
      router.push({
        path: '/login',
      }).then(() => {
        multiTabStore.clear()
        layoutMenuStore.clear()
      })
    }
  }
  else {
    resetPassword()
    // const hide = message.loading('退出登录...', 0)
  }
}
// 打开修改密码弹窗
function resetPassword(record) {
  if (passwordForm.value) {
    passwordForm.value.resetFields()
  }
  passwordOpen.value = true
}
// 确认修改密码
async function handleOk() {
  try {
    await passwordForm.value.validate()
    // const params = {
    //   userId,
    //   oldPwd: Secret.encrypt(formState.oldPwd),
    //   newPwd: Secret.encrypt(formState.newPwd),
    // }
    // console.log(params)
    formState.oldPwd = Secret.encrypt(formState.oldPwd)
    formState.newPwd = Secret.encrypt(formState.newPwd)
    formState.confirmPass = Secret.encrypt(formState.confirmPass)
    const { data } = await updatePwd(formState)
    console.log(data)
    message.success('修改成功')
    passwordOpen.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
</script>

<template>
  <a-dropdown>
    <span hover="bg-[var(--hover-color)]" flex items-center h-48px px-12px cursor-pointer class="transition-all-300">
      <a-avatar src="https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png" mr-8px size="small" />
      <span class="anticon">{{ username }}</span>
    </span>
    <template #overlay>
      <a-menu @click="handleClick">
        <a-menu-item key="0">
          <template #icon>
            <KeyOutlined />
          </template>
          <!-- <RouterLink to="/account/center"> -->
          修改密码
          <!-- </RouterLink> -->
        </a-menu-item>
        <!-- <a-menu-item key="1">
          <template #icon>
            <ProfileOutlined />
          </template>
          <RouterLink to="/account/settings">
            个人设置
          </RouterLink>
        </a-menu-item> -->
        <a-menu-divider />
        <a-menu-item key="logout">
          <template #icon>
            <LogoutOutlined />
          </template>
          退出登录
        </a-menu-item>
      </a-menu>
    </template>
  </a-dropdown>
  <!-- 添加银行账户 -->
  <a-modal v-model:open="passwordOpen" width="600px" title="修改密码" :mask-closable="false" :body-style="{ paddingTop: '30px', paddingBottom: '30px' }" ok-text="确定" @ok="handleOk">
    <a-form
      ref="passwordForm"
      :model="formState"
      :rules="rules"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
    >
      <a-form-item
        label="旧密码："
        name="oldPwd"
      >
        <a-input-password v-model:value="formState.oldPwd" placeholder="请输入旧密码" />
      </a-form-item>
      <a-form-item
        label="新密码："
        name="newPwd"
      >
        <a-input-password v-model:value="formState.newPwd" placeholder="请输入新密码" />
      </a-form-item>
      <a-form-item
        label="确认密码："
        name="confirmPass"
      >
        <a-input-password v-model:value="formState.confirmPass" placeholder="请确认密码" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
